package com.bd.dao;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.bd.model.CD;

@Repository
public class CDDaoImpl extends Dao<CD> implements CDDao {

	@Override
	public Class<CD> getEntityClass() {
		return CD.class;
	}

	@Override
	public List<CD> findByExample(CD cd) {
		SimpleDateFormat spdf = new SimpleDateFormat("yyyy-MM-dd");
		StringBuilder builder = createBuilder();
		if (cd.getId() != null && cd.getId() > 0)
			builder.append(" AND id LIKE '%" + cd.getId() + "%'");
		if (cd.getFkLabel() != null)
			builder.append(" AND fkLabel = " + cd.getFkLabel().getId());
		builder.append(" AND descricao LIKE '%" + cd.getDescricao() + "%'");
		if (cd.getPreco() != null)
			builder.append(" AND preco BETWEEN 0 AND " + cd.getPreco());
		if (cd.getDataCompra() != null)
			builder.append(" AND dataCompra = '" + spdf.format(cd.getDataCompra()) + "'");
		if (cd.getDataGravacao() != null)
			builder.append(" AND dataGravacao = '" + spdf.format(cd.getDataGravacao()) + "'");

		builder.replace(builder.indexOf("AND"), builder.indexOf("AND") + 3, "");
		System.out.println(builder.toString());
		Query q = getEm().createQuery(builder.toString());

		return (List<CD>) q.getResultList();
	}

}
